package cn.dduan.fool.design.pattern.great.single;

import java.util.HashMap;
import java.util.Map;

/**
 * 登记式单例（不推荐）
 * <p>
 * 原理：实际上维护了一组单例类的实例，将这些实例存放在一个Map（登记薄）中，对于已经登记过的实例，则从Map直接返回，对于没有登记的，则先登记，然后返回
 *
 * @author dduan
 * @version 1.0
 * @date 2023/3/17
 */
public class RegisterSingletion {
    private static Map<String, RegisterSingletion> map = new HashMap<String, RegisterSingletion>();

    static {
        RegisterSingletion single = new RegisterSingletion();
        map.put(single.getClass().getName(), single);
    }

    //保护的默认构造子
    protected RegisterSingletion() {
    }

    //静态工厂方法,返还此类惟一的实例
    public static RegisterSingletion getInstance(String name) {
        if (name == null) {
            name = RegisterSingletion.class.getName();
            System.out.println("name == null" + "--->name=" + name);
        }
        if (map.get(name) == null) {
            try {
                map.put(name, (RegisterSingletion) Class.forName(name).newInstance());
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
        return map.get(name);
    }

    //一个示意性的商业方法
    public String about() {
        return "Hello, I am RegSingleton.";
    }

    public static void main(String[] args) {
        RegisterSingletion single = RegisterSingletion.getInstance(null);
        System.out.println(single.about());
    }
}
